package com.code.bolg.service.impl;

import com.code.bolg.bean.User;
import com.code.bolg.enums.DelFlagEnum;
import com.code.bolg.enums.ResultEnum;
import com.code.bolg.exception.BolgExcetion;
import com.code.bolg.repository.UserRepository;
import com.code.bolg.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User save(User user) {
        User save = userRepository.save(user);
        return save;
    }

    @Override
    public int deleteById(int id) {

        Optional<User> optional= userRepository.findById(id);
        if(optional.isPresent()){
            userRepository.deleteById(id);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public User findById(int id) {
        Optional<User> optional = userRepository.findById(id);
        if (optional.isPresent()) {
            User user = optional.get();
            return user;
        } else {
            throw new BolgExcetion(ResultEnum.NOTFINDDATA);
        }
    }

    @Override
    public User find(User user) {
        Example<User> example = Example.of(user);
        List<User> all = userRepository.findAll(example);
        if(all==null|| all.size()==0||all.get(0)==null){
             throw  new BolgExcetion(ResultEnum.NOTFINDUSER);
        }
        return all.get(0);
    }

    @Override
    public List<User> findAll(User user, int page, int size) {
        Sort sort = new Sort(Sort.Direction.DESC, "gmtCreate");
        //分页构造
        Pageable pageable = PageRequest.of(page,size,sort);
        Example<User> example = Example.of(user);
        Page<User> all = userRepository.findAll(example,pageable);
        return  all.getContent();
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }


    @Override
    public List<User> findAll(int page, int size) {
        User s = new User();
        s.setDelFlag(DelFlagEnum.NOTDELETE.getCode());
        Sort sort = new Sort(Sort.Direction.DESC, "gmtCreate");
        //分页构造
        Pageable pageable = PageRequest.of(page,size,sort);
        Example<User> example = Example.of(s);
        Page<User> all = userRepository.findAll(example,pageable);
        return  all.getContent();
    }
}
